﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using TransControlSystem.Dao;
using TransControlSystem.Model;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel.Common
{
    public class EditUserViewModel : ViewModelBase
    {
        /// <summary>
        /// 隐藏窗体命令
        /// </summary>
        public DelegateCommand HideEditUserWindowCommand { get; set; }

        /// <summary>
        /// 保存用户
        /// </summary>
        public DelegateCommand SaveUserCommand { get; set; }

        //用户信息
        private User _UserIfo = new User();
        /// <summary>
        /// 用户信息
        /// </summary>
        public User UserIfo
        {
            get
            {
                return _UserIfo;
            }
            set
            {
                _UserIfo = value;
                RaisePropertyChanged("UserIfo");
            }
        }
        /// <summary>
        /// 下拉框列表
        /// </summary>
        private ObservableCollection<User> _ComBoxItems;
        public ObservableCollection<User> ComBoxItems
        {
            get
            {
                return _ComBoxItems;
            }
            set
            {
                _ComBoxItems = value;
                RaisePropertyChanged("ComBoxItems");
            }
        }

        /// <summary>
        /// 下拉框当前选中
        /// </summary>
        private User _CurrentlySelectedItem;
        public User CurrentlySelectedItem
        {
            get
            {
                return _CurrentlySelectedItem;
            }
            set
            {
                _CurrentlySelectedItem = value;
                RaisePropertyChanged("CurrentlySelectedItem");
            }
        }


        /// <summary>
        /// Constructors
        /// </summary>
        public EditUserViewModel()
        {
            //初始化下拉框
            ComBoxItems = new ObservableCollection<User>();
            User user = new User();
            user.Role = "system";
            ComBoxItems.Add(user);
            user = new User();
            user.Role = "guest";
            ComBoxItems.Add(user);
            //初始化隐藏窗体命令
            HideEditUserWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideEditUserWindowHandler)
            };
            //初始化保存命令
            SaveUserCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SaveUserWindowHandler)
            };
        }
        /// <summary>
        /// 保存处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void SaveUserWindowHandler(object obj)
        {
            try
            {
                if (UserIfo.Password == null || UserIfo.Password.Trim() == "")
                {
                    //警告 必须填写密码
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写密码。");
                    return;
                }
                else if (UserIfo.Password.Trim().Length < 6)
                {
                    //警告 密码至少6位
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写至少六位密码。");
                    return;
                }
                else if (UserIfo.Password.Trim().Length > 20)
                {
                    //警告 密码不可超过20位
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写的密码不可超过20位。");
                    return;
                }
                else if (XyhUtils.IsHasSQLInject(XyhUtils.Encrypt(UserIfo.Password)))
                {
                    WindowManager.ShowWarning("警告", "密码不可用包含SQL注入关键词！");
                    return;
                }
                if (UserIfo.Role == null || UserIfo.Role.Trim() == "")
                {
                    //警告 必须选择角色
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您必须选择角色。");
                    return;
                }
                string sql = "update [User] set Password = '" + XyhUtils.Encrypt(UserIfo.Password) + "',  Role = @Role where Id = @Id";
                int result = DapperTools.Update<User>(sql, UserIfo);
                if (result > 0)
                {
                    WindowManager.ShowWarning("提示", "尊敬的用户，您修改用户信息成功。");
                    Application.Current.Dispatcher.Invoke((Action)delegate ()
                    {
                        UserIfo = new User();
                    });
                    Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "ReLoadUserQueue"));
                    Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideEditUserWindow"));
                }
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "编辑用户异常");
            }
        }

        /// <summary>
        /// 隐藏本窗体处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void HideEditUserWindowHandler(object obj)
        {
            Application.Current.Dispatcher.Invoke((Action)delegate ()
            {
                UserIfo = new User();
            });
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideEditUserWindow"));
        }

        /// <summary>
        /// 加载用户数据
        /// </summary>
        /// <param name="IncomingUser">被编辑的用户</param>
        public void LoadUserInfo(User IncomingUser)
        {
            Application.Current.Dispatcher.Invoke((Action)delegate ()
            {
                UserIfo = DapperTools.Query<User>("select * from [User] WHERE Id = @Id", IncomingUser);
                UserIfo.Password = XyhUtils.Decrypt(UserIfo.Password);
                for (int i = 0; i < ComBoxItems.Count; i++)
                {
                    if (ComBoxItems[i].Role == UserIfo.Role)
                    {
                        CurrentlySelectedItem = ComBoxItems[i];
                        break;
                    }
                }

            });
        }
    }
}
